#!/usr/bin/env python
# -*- coding:utf-8 -*-  

import os
import sys
import fnmatch
import re
import subprocess
import glob
import shutil
import types
from biplist import *

def find_replace(dir, to_be_replaced, replacement):
  for parent, dirnames, filenames in os.walk(dir):
    for filename in filenames:
      old_file = os.path.join(parent, filename)
      new_file = os.path.join(parent, filename.replace(to_be_replaced, replacement))
      # print(old_file + ' --> ' + new_file)
      os.rename(old_file, new_file)

      # print('filename->' + filename)
      if filename.split(".")[-1] in ['DS_Store', 'png', 'jpg', 'jpeg', 'xcuserstate']:
        continue

      if filename.split('.')[-1] == 'plist':
        file = os.path.join(parent, filename)
        plist=readPlist(file)
        for key in plist.keys():
          if type(plist[key]) == type('a'):
            plist[key] = plist[key].replace(to_be_replaced, replacement) 

        writePlist(plist, file)
        continue
      try:
        with open(new_file) as f:
            data = f.read()
        with open(new_file, 'w') as f:
            data = re.sub(to_be_replaced, replacement, data)
            f.write(data)
      finally:
        pass

  for parent, dirnames, filenames in os.walk(dir, topdown=False):
    for dirname in dirnames:
      old_dir = os.path.join(parent, dirname)
      new_dir = os.path.join(parent, dirname.replace(to_be_replaced, replacement))
      # print(old_dir + ' --> ' + new_dir)
      os.rename(old_dir, new_dir)

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print('---pls---enter--the--name--of--the--COMMON--LIB---')
        sys.exit(-1)
    dir = sys.argv[1] 
    to_be_replaced = sys.argv[2]  
    replacement = sys.argv[3] 
    find_replace(dir, to_be_replaced, replacement)